//
//  SearachViewController.m
//  ebook
//
//  Created by ChenNan on 16/3/23.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "SearachViewController.h"
#import "EbookNetRequest.h"
#import "BannerAdView.h"
#import "InterstitialAdView.h"
#import "PushWebviewViewController.h"
#import "UIView+Extension.h"
#import "SearchTableViewCell.h"

#define kSearchControllerResultCellID @"cellId"
@interface SearachViewController ()<UISearchBarDelegate, UIWebViewDelegate, UIScrollViewDelegate,BannerAdViewDelegate,UITableViewDataSource,UITableViewDelegate>{
    BOOL hasSearch;//是否开始了搜索
}

@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *searchResults;
@property (nonatomic, retain) UIImageView *resultBgView;

@property (nonatomic, retain) BannerAdView *bannerAdView;//条幅广告
@property (nonatomic, retain) InterstitialAdView *interstitialAdView;//插屏广告

@end

@implementation SearachViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = MTConfigColor(@"MTSearch_Bg_Color");
    _searchResults = [NSMutableArray array];
    
    self.webView.frame = CGRectMake(0, 0, MTScreenW, MTScreenH-SafeAreaTopHeight);
    [self.view addSubview:self.webView];
    if(iOS8)((WKWebView*)self.webView).scrollView.delegate = self;
    else ((UIWebView*)self.webView).scrollView.delegate = self;
    
    NSDictionary *dict = kBookCityDataDict;
    NSString *homeUrl = dict[@"data"][@"search"][@"index"];
    [self webView:self.webView loadUrl:homeUrl];
    
    [self createBackBtn];
    [self createSearchBar];
    
    [self setAd];
}

-(UITableView *)tableView{
    
    if(!_tableView){
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,MTScreenW, MTScreenH-SafeAreaTopHeight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.9];
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

-(void)setAd{
    
    //底部条幅广告
    _bannerAdView = [[BannerAdView alloc]init];
    _bannerAdView.delegate = self;
    [_bannerAdView showAdInController:self location:BannerAdInSearch];
    
    //显示插屏广告
    _interstitialAdView = [[InterstitialAdView alloc] init];
    [_interstitialAdView showAdInController:self size:CGSizeMake(kAdWidth, kAdHeight) closeTime:-20 location:InterAdInSearch];//不自动关闭的插屏
}

//广告显示成功后再回过头来设置条幅广告的高度
-(void)bannerAdView:(BannerAdView *)view didLoadBannerAdHeight:(float)height{
    
    self.webView.frame = CGRectMake(0, 0, MTScreenW, MTScreenH-SafeAreaTopHeight-height);
}

-(void)bannerAdViewClose:(BannerAdView *)view{
   
    self.webView.frame = CGRectMake(0, 0, MTScreenW, MTScreenH-SafeAreaTopHeight);
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

#pragma mark - searchBar
- (void)createSearchBar
{
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.contentMode = UIViewContentModeLeft;
    searchBar.placeholder = @"输入书名/作者";
    searchBar.delegate = self;
    _searchBar = searchBar;
    [searchBar becomeFirstResponder];
    self.navigationItem.titleView = searchBar;
    if(iOS11){
        [[searchBar.heightAnchor constraintEqualToConstant:44.0] setActive:YES];
    }
}

#pragma mark - backBtn
- (void)createBackBtn
{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    backItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
    //    TableViewController *tvc = [[TableViewController alloc]init];
    //    [self.navigationController pushViewController:tvc animated:YES];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    NSDictionary *dic = [self getDefaultDic];
    NSString *searchIndex = dic[@"data"][@"search"][@"get"];
    NSString *searchUrlStr = [NSString stringWithFormat:@"%@?w=%@",searchIndex,searchBar.text];
    searchUrlStr = [searchUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self webView:self.webView loadUrl:searchUrlStr];
    hasSearch = YES;
    
    [searchBar resignFirstResponder];
    [self.tableView removeFromSuperview];
    [self.resultBgView removeFromSuperview];
    [_interstitialAdView dismiss];
}

//searchBar中没有文字，webView 加载起始url
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    MTLog(@"searchText:%@",searchText);
    if (0 == searchText.length) {
        
        NSDictionary *dic = [self getDefaultDic];
        NSString *homeUrl = dic[@"data"][@"search"][@"index"];
        [self webView:self.webView loadUrl:homeUrl];
        [_searchResults removeAllObjects];
        [self.tableView reloadData];
        [self.tableView removeFromSuperview];
        [_resultBgView removeFromSuperview];
    }else{
        
        hasSearch = NO;
        [EbookNetRequest searchText:searchText resultSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
            NSArray *result = [dict objectForKey:@"data"];
            if(![result isKindOfClass:[NSNull class]])// && result.count>0
            {
                
                [_searchResults removeAllObjects];
                [_searchResults addObjectsFromArray:result];
                [self.tableView reloadData];
                self.tableView.height = self.searchResults.count*44;
                
                [_resultBgView removeFromSuperview];
//                UIImage *image = [UIImage imageNamed:@"table_line_bg"];
//                _resultBgView = [[UIImageView alloc]initWithFrame:self.tableView.bounds];
//                _resultBgView.width = MTScreenW;
//                _resultBgView.clipsToBounds = YES;
//                _resultBgView.image = [self getSubImage:image mCGRect:CGRectMake(0, 2, MTScreenW, self.tableView.height) centerBool:NO];
//                [_resultBgView setAlpha:0.9];
                
                if(!hasSearch){
                    [self.view addSubview:_resultBgView];
                    [self.view addSubview:self.tableView];
                }
            }
        } failed:^(int stateCode, NSString *failMsg) {
            MTLog(@"");
        }];
    }
}

/**
 * 截取部分图像
 *
 **/
-(UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect centerBool:(BOOL)centerBool
{
    /*如若centerBool为Yes则是由中心点取mCGRect范围的图片*/
    float imgwidth = image.size.width;
    float imgheight = image.size.height;
    float viewwidth = mCGRect.size.width;
    float viewheight = mCGRect.size.height;
    CGRect rect;
    if(centerBool)
        rect = CGRectMake((imgwidth-viewwidth)/2, (imgheight-viewheight)/2, viewwidth, viewheight);
    else{
        if (viewheight < viewwidth) {
            if (imgwidth <= imgheight) {
                rect = CGRectMake(0, 0, imgwidth, imgwidth*viewheight/viewwidth);
            }else {
                float width = viewwidth*imgheight/viewheight;
                float x = (imgwidth - width)/2 ;
                if (x > 0) {
                    rect = CGRectMake(x, 0, width, imgheight);
                }else {
                    rect = CGRectMake(0, 0, imgwidth, imgwidth*viewheight/viewwidth);
                }
            }
        }else {
            if (imgwidth <= imgheight) {
                float height = viewheight*imgwidth/viewwidth;
                if (height < imgheight) {
                    rect = CGRectMake(0, 0, imgwidth, height);
                }else {
                    rect = CGRectMake(0, 0, viewwidth*imgheight/viewheight, imgheight);
                }
            }else {
                float width = viewwidth*imgheight/viewheight;
                if (width < imgwidth) {
                    float x = (imgwidth - width)/2 ;
                    rect = CGRectMake(x, 0, width, imgheight);
                }else {
                    rect = CGRectMake(0, 0, imgwidth, imgheight);
                }
            }
        }
    }
    
    CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
    
    UIGraphicsBeginImageContext(smallBounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, smallBounds, subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();
    
    return smallImage;
}


- (NSDictionary *)getDefaultDic {
    
    id data = [[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData];
    return  [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [_searchBar resignFirstResponder];
}

#pragma mark 搜索联想结果展示

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _searchResults.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSearchControllerResultCellID];
    if (!cell) {
        cell = [[SearchTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kSearchControllerResultCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    NSDictionary *dict = self.searchResults[indexPath.row];
    cell.textLabel.text = dict[@"name"];
    //    cell.detailTextLabel.text = dict[@"Author"];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dict = self.searchResults[indexPath.row];
    _searchBar.text = dict[@"name"];
    [self searchBarSearchButtonClicked:_searchBar];
}

-(void)dealloc{
    _interstitialAdView = nil;
    _bannerAdView = nil;
}

@end
